package cn.luo.service;

import cn.luo.dao.BlogsDao;
import cn.luo.dao.TagDao;
import cn.luo.entity.Blogs;
import cn.luo.entity.Content;
import cn.luo.entity.Tag;
import cn.luo.uilt.DigestText;
import cn.luo.uilt.SessionUitls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

@Service
public class BlogsServiceImpl implements BlogsService {
    @Autowired
    BlogsDao blogsDao;

    @Autowired
    TagDao tagDao;

    //分页查询
    @Override
    public List<Blogs> finfByPage(int start, int num) {
        Integer startx = (start-1) * num;
        return blogsDao.findByPage(startx,num);
    }

    @Override
    public long total() {
        return blogsDao.total();
    }

    //添加博文
    @Transactional
    @Override
    public void addboke(@RequestBody Map<String, Object> map) {
        Content content = new Content();
        Blogs blogs = new Blogs();

        //添加内容
        content.setContent((String)map.get("content"));
        blogsDao.addboke(content);

        //关联类型
        blogs.setTagid((String) map.get("tagid"));

        blogs.setTitle((String)map.get("title"));
        System.out.println("getNickname====" + SessionUitls.getUser());
        blogs.setAuthor(SessionUitls.getNickname());  //获取作者名字,跟博文表绑定
        blogs.setUid(SessionUitls.getUid());           //从session中拿到用户id，和博文关联
        blogs.setContentid(content.getId()); //拿到内容id，获取内容

        //截取摘要
        StringBuffer strb = new StringBuffer();;
        String s = content.getContent();
        String s1 = DigestText.html2Text(s);
        System.out.println("strb = " + strb.toString());
        blogs.setDigest(s1);
        System.out.println("blogs = " + blogs);
        blogsDao.addTitle(blogs);
    }

    //根据blogs ID 查找
    @Override
    public Blogs findByBlogsId(String id) {
        return blogsDao.findByBlogsId(id);
    }

    //类型分页查询
    @Override
    public List<Blogs> findByPageByTagId(int start, int num, String tagid) {
        Integer s = (start-1) * num;
        return blogsDao.findByPageByTagId(s,num,tagid);
    }

    //统计类型总数
    @Override
    public long tagtotal(String tagid) {
        return blogsDao.tagtotal(tagid);
    }
}
